//
//  CNSearchView.m
//  BeeQuick_19
//
//  Created by whong7 on 16/9/23.
//  Copyright © 2016年 CN Team. All rights reserved.
//

#import "CNSearchView.h"
#import "CNSearchFlowLayout.h"
#import "CNSearchViewModel.h"
#import "CNSearchViewCell.h"
#import "CNSearchModel.h"
#import "CNSearchReusableView.h"

@interface CNSearchView ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong)CNSearchReusableView *searchHeader;

@property(nonatomic,strong)NSArray *dataArray;


@end

@implementation CNSearchView
//collectionView：id
static NSString *cellid = @"id-cell";

#pragma mark - 程序入口
-(instancetype)initWithFrame:(CGRect)frame
{
    
    CNSearchFlowLayout *flowLayout = [[CNSearchFlowLayout alloc]init];
    self = [super initWithFrame:frame collectionViewLayout:flowLayout];
    if(self)
    {
        [self setupUI];
    }
    return self;
}


-(void)awakeFromNib
{
    [super awakeFromNib];
    [self setupUI];
    
}

-(void)setupUI
{
    // 添加下拉刷新
    self.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [SVProgressHUD showWithStatus:@"正在加载"];
        [self loadData];
        
    }];
    //此方法会自动调用下拉刷新绑定的方法
    [self.mj_header beginRefreshing];
    
    self.backgroundColor = [UIColor colorWithHex:0xefefef];

    //注册xib单元格
    UINib *nib = [UINib nibWithNibName:@"CNSearchViewCell" bundle:nil];
    [self registerNib:nib forCellWithReuseIdentifier:cellid];
    
    //注册headerView Nib的view需要继承UICollectionReusableView
    [self registerNib:[UINib nibWithNibName:@"CNSearchReusableView" bundle:nil]forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerid"];
    self.delegate = self;
    self.dataSource = self;
    
    [self loadData];
}

#pragma mark - 加载数据
-(void)loadData
{
    //有网络链接的时候去加载
    if ([self reach])
    {
        __weak typeof(self) weakSelf = self;
        [CNSearchViewModel loadDataWithBlock:^(NSArray *dataArray) {
            if (dataArray) {
                
                //用于遍历的数组
                NSMutableArray *dataA = [NSMutableArray array];
                //根据搜索字符，对数据进行二次加载
                for (CNSearchModel *wModel in dataArray.copy) {
                    if ([wModel.name containsString:self.searchStr]) {
                        [dataA addObject:wModel];
                    }
                }
                self.dataArray = dataA;
                
                NSLog(@"%@",weakSelf.dataArray);
                [SVProgressHUD dismiss];
                //2. 停止刷新
                [self.mj_header endRefreshing];
                [weakSelf reloadData];
                weakSelf.loadBock(YES);
            }
            else
            {
                NSLog(@"数据错误");
            }
            
        }];

    }
}

#pragma mark - 代理方法
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//有多少块
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
//cell的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CNSearchModel *model = self.dataArray[indexPath.row];
    CNSearchViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellid forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];

    cell.model = model;
    cell.indexPath = indexPath;
    __weak typeof(self) weakSelf = self;
    cell.cellBlock = ^(NSIndexPath * indexPath, NSInteger selfCount)
    {
        //解决cell复用问题
        CNSearchModel *model = weakSelf.dataArray[indexPath.row];
        model.count = selfCount;
    };
    return cell;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        CNSearchReusableView* heaerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerid" forIndexPath:indexPath];
        [heaerView.mixButton addTarget:self action:@selector(mixButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [heaerView.priceButton addTarget:self action:@selector(priceButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [heaerView.sellButton addTarget:self action:@selector(sellButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        self.searchHeader = heaerView;
        
        return heaerView;
    }
    return nil;
}



#pragma mark - 点击事件
//综合排序
- (void)mixButtonClick:(UIButton *)sender {
    
    self.searchHeader.mixButton.selected = YES;
    self.searchHeader.priceButton.selected = NO;
    self.searchHeader.sellButton.selected = NO;
    
    self.dataArray = [self.dataArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        CNSearchModel *mixModel1 = obj1;
        CNSearchModel *mixModel2 = obj2;
        
        
        //排序
        if (mixModel1.goods_id > mixModel2.goods_id) { //不使用intValue比较无效
            return NSOrderedDescending;//降序
        }else if (mixModel1.goods_id < mixModel2.goods_id){
            return NSOrderedAscending;//升序
        }else {
            return NSOrderedSame;//相等
        }  
        
    }];
    [self reloadData];
    
}
//按价格排序
- (void)priceButtonClick:(id)sender {
    
    self.searchHeader.mixButton.selected = NO;
    self.searchHeader.priceButton.selected = YES;
    self.searchHeader.sellButton.selected = NO;
    
    self.dataArray = [self.dataArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        CNSearchModel *mixModel1 = obj1;
        CNSearchModel *mixModel2 = obj2;
        
        
        //排序
        if (mixModel1.partner_price > mixModel2.partner_price) { //不使用intValue比较无效
            return NSOrderedDescending;//降序
        }else if (mixModel1.partner_price < mixModel2.partner_price){
            return NSOrderedAscending;//升序
        }else {
            return NSOrderedSame;//相等
        }
        
    }];
    [self reloadData];
    
}
//按销量
- (void)sellButtonClick:(id)sender {
    
    self.searchHeader.mixButton.selected = NO;
    self.searchHeader.priceButton.selected = NO;
    self.searchHeader.sellButton.selected = YES;
    
    self.dataArray = [self.dataArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        CNSearchModel *mixModel1 = obj1;
        CNSearchModel *mixModel2 = obj2;
        
        
        //排序
        if (mixModel1.number > mixModel2.number) { //不使用intValue比较无效
            return NSOrderedDescending;//降序
        }else if (mixModel1.number < mixModel2.number){
            return NSOrderedAscending;//升序
        }else {
            return NSOrderedSame;//相等
        }
        
    }];
    [self reloadData];
    
}

#pragma mark - 检测网络连接
- (BOOL)reach
{
    __block BOOL inNet = YES;
    /**
     AFNetworkReachabilityStatusUnknown          = -1,  // 未知
     AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
     AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱
     AFNetworkReachabilityStatusReachableViaWiFi = 2,   // 局域网络,不花钱
     */
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    __weak typeof(self) weakSelf = self;
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case -1:
//                NSLog(@"未知");
                break;
            case 0:
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"请检查网络是否连接"]];
                inNet = NO;
                [self.mj_header endRefreshing];
                break;
            case 1:
//                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"3G 花钱"]];
                break;
            case 2:
//                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"局域网络,不花钱"]];
                break;
            default:
                break;
        }
    }];
    return inNet;
}



@end
